package training;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author liangzai
 * @Description:
 */
public class J25_6_23_Training {
    //k 镜像数字的和
    private int n;
    private long sum = 0;
    public long kMirror(int k, int n) {
        this.n = n;
        for (int i = 1; i <= 19 && this.n > 0; i++) {
            dfs(new char[i], i, 0, k);
        }
        return sum;
    }
    private void dfs(char[] chs, int len, int index, int k) {
        if (index > (len - 1) >> 1) {
            if (f(chs, k)){
                sum += Long.parseLong(new String(chs));
                this.n--;
            }
            return;
        }
        for (int i = index == 0 ? 1 : 0; i < 10 && this.n > 0; i++) {
            chs[index] = (char) (i + '0');
            chs[len - 1 - index] = (char) (i + '0');
            dfs(chs, len, index + 1, k);
        }
    }
    private boolean f(char[] chs, int k) {
        List<Character> list = new ArrayList<>();
        long p = Long.parseLong(new String(chs));;
        while (p > 0) {
            list.add((char) (p%k + '0'));
            p = p/k;
        }
        int size = list.size();
        int i = 0;
        while (i <= (size - 1) >> 1) {
            if (list.get(i) != list.get(size - 1 - i)) {
                return false;
            }
            i++;
        }
        return true;
    }
}
